package com.tgh.au.c5;

import java.util.concurrent.TimeUnit;

import com.tgh.au.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.view.KeyEvent;
import android.view.View;

public class GameView6 extends View implements Runnable {
	Bitmap qq;
	Bitmap destTop;
	int DTX=0;
	
	public GameView6(Context context) {
		super(context);
		setFocusable(true);
		requestFocus();
		DTX=0;
		
		qq=BitmapFactory.decodeResource(context.getResources(), R.drawable.qq);
		destTop=BitmapFactory.decodeResource(getResources(), R.drawable.desktop);
		new Thread(this).start();
	}
	protected void onDraw(Canvas canvas) {
		canvas.drawColor(Color.GRAY);
		drawImage(canvas, qq, 0, 0);
		drawImage(canvas, destTop, DTX, qq.getHeight(), destTop.getWidth(), destTop.getHeight()/2, 0, 0);
	}
	/**
	 * 绘制图片，将图片绘制到屏幕上的指定位置，并对图片作剪裁
	 * @param canvas 画布
	 * @param bitmap 图片
	 * @param x 屏幕上的x坐标
	 * @param y	屏幕上的y坐标
	 * @param w	要绘制图片的宽度
	 * @param h 要绘制图片的高度
	 * @param bx 图片上的x坐标
	 * @param by 图片上的y坐标
	 */
	public static void drawImage(Canvas canvas,Bitmap bitmap,int x,int y,int w,int h,int bx,int by) {
		//图片剪裁区域
		Rect src=new Rect();
		//屏幕剪裁区域
		Rect dst=new Rect();
		
		src.left=bx;
		src.top=by;
		src.right=bx+w;
		src.bottom=by+h;
		
		dst.left=x;
		dst.top=y;
		dst.right=x+w;
		dst.bottom=y+h;
		
		canvas.drawBitmap(bitmap, src, dst, null);
		src=null;
		dst=null;
	}
	/**
	 * 绘制图片
	 * @param canvas
	 * @param bitmap
	 * @param x 屏幕上的x坐标
	 * @param y 屏幕上的y坐标
	 */
	public static void drawImage(Canvas canvas,Bitmap bitmap,int x,int y) {
		canvas.drawBitmap(bitmap, x, y, null);
	}
	
	@Override
	public void run() {
		while (!Thread.currentThread().isInterrupted()) {
			try {
				TimeUnit.MILLISECONDS.sleep(100);
			} catch (Exception e) {
				Thread.currentThread().interrupt();
			}
			postInvalidate();
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if (DTX>0) {
				DTX--;
			}
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if (DTX+destTop.getWidth()<320) {
				DTX++;
			}
			break;
		}
		return true;
	}
	
}
